<?php
namespace Home\Controller;
use Think\Controller;
use Think;
use Think\Model;


class AuthController extends Controller {
    public $config=[];
    public $game_server=[];
    // 类似于构造函数一样
    public function _initialize(){// 调用的时候，直接执行 就可以了
       $this->config= include dirname(dirname(__DIR__)).'/Common/conf/config.php';
       $this->checkLogin();
       $this->checkRule();
       $query= parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY);
       parse_str($query,$_GET);
       $this->game_server= $this->game("select ServerID,ServerName,KindID from cfg_gameroominfo");
    }

    /**
     * 检测是否登录
     */
    public function checkLogin(){

        if(!$_SESSION['ltq_game_admin_user']['id']){
            $this->redirect('User/login', array(), 1, 'Please login ...');
        }else{
            $id=(int)$_SESSION['ltq_game_admin_user']['id'];
            $users =$this->weblog("SELECT * from ltq_admin where id=$id");
            //echo $_SESSION['ltq_game_admin_user']['session_id'];
            $session_id=$users[0]['session_id'];  //数据库
            if($session_id != $_SESSION['ltq_game_admin_user']['session_id']){
                $this->redirect('User/login', array(), 1, '另一台机器正在登录您的账号,您已下线');
            }
        }
                session_write_close();
        
    }

    


    /**
     * 检测是否有用权限
     */
    public function checkRule(){
        $role = $this->getRoleStateBySessionId();
        
        $this->assign("role",$role);
    }
    
    //通过游戏ID获取游戏名称
    public function GetGameNameByID($id){
        foreach ($this->game_server as $value) {
            if($value[ServerID]==$id)
                return $value[ServerName];
        }
        return "";
    }
    
    //获取游戏类型
    public function GetAllGameType(){
        $info=[];
        $info['全部']=['全部',-1];
        foreach ($this->game_server as $value) {
            $pos= strpos($value[ServerName], '(');
            $name= substr($value[ServerName], 0,$pos);
            $info[$name]=[$name,$value[KindID]];
        }
        return $info;
    }
    
    //获取游戏类型服务器id集合
    public  function GetGameServerIDs($type){
        $info=[];
        foreach ($this->game_server as $value) {
            if($value[KindID]==$type){
                $info[]=$value[ServerID];
            }
        }
        return $info;
    }

    /*
     * 根据角色role 获取角色说明
     */
    protected function getRoleStateBySessionId(){
        if($_SESSION["ltq_user"]["role"]==1){
            $data['Name']="管理员";
            $data['State']="可以自由分配所以权限";
        }
        if($data['role']==2){
            $data['Name']="研发人员";
            $data['State']= "拥有系统数据的操作权限";
        }
        if($data["role"]==3){
            $data["Name"]="运营人员";
            $data['State']="拥有管理员分配的权限";
        }
        if($data['role']==4){
            $data['Name']="客服人员";
            $data['State']="拥有管理员分配的权限";
        }
        $role=$data;
        return $role;
    }
    //根据游戏种类ID 获取游戏名称
    function selects(){
        $str[] = ['kindid'=>2,'name'=>'抢庄牛牛'];
        $str[] = ['kindid'=>3,'name'=>'通比牛牛'];
        $str[] = ['kindid'=>5,'name'=>'百人牛牛'];
        $str[] = ['kindid'=>10,'name'=>'通比炸金花'];
        $str[] = ['kindid'=>20,'name'=>'百人炸金花'];
        $str[] = ['kindid'=>30,'name'=>'炸金花'];
        $str[] = ['kindid'=>50,'name'=>'幸运水果机'];
        $str[] = ['kindid'=>60,'name'=>'百家乐'];
        $str[] = ['kindid'=>61,'name'=>'龙虎斗'];
        $str[] = ['kindid'=>62,'name'=>'红黑大战'];
        $str[] = ['kindid'=>65,'name'=>'21点'];
        $str[] = ['kindid'=>80,'name'=>'财神来了'];
        $str[] = ['kindid'=>81,'name'=>'水浒传'];
        $str[] = ['kindid'=>85,'name'=>'森林舞会'];
        return $str;
    }
    //根据游戏ID 获取游戏名称
    function getGameGerverId(){
        /*$str[] = ['ServerID'=>31,'kindid'=>5,'ServerName'=>'百人牛牛(五倍场)'];
        $str[] = ['ServerID'=>32,'kindid'=>5,'ServerName'=>'百人牛牛(十倍场)'];
        $str[] = ['ServerID'=>40,'kindid'=>60,'ServerName'=>'百家乐(房间1)'];
        $str[] = ['ServerID'=>41,'kindid'=>60,'ServerName'=>'百家乐(房间2)'];
        $str[] = ['ServerID'=>42,'kindid'=>60,'ServerName'=>'百家乐(房间3)'];
        $str[] = ['ServerID'=>43,'kindid'=>60,'ServerName'=>'百家乐(房间4)'];
        $str[] = ['ServerID'=>44,'kindid'=>60,'ServerName'=>'百家乐(房间5)'];
        $str[] = ['ServerID'=>45,'kindid'=>60,'ServerName'=>'百家乐(房间6)'];
        $str[] = ['ServerID'=>50,'kindid'=>61,'ServerName'=>'龙虎斗'];
        $str[] = ['ServerID'=>60,'kindid'=>62,'ServerName'=>'红黑大战'];
        $str[] = ['ServerID'=>70,'kindid'=>2,'ServerName'=>'抢庄牛牛(新手场)'];
        $str[] = ['ServerID'=>71,'kindid'=>2,'ServerName'=>'抢庄牛牛(初级场)'];
        $str[] = ['ServerID'=>72,'kindid'=>2,'ServerName'=>'抢庄牛牛(中级场)'];
        $str[] = ['ServerID'=>73,'kindid'=>2,'ServerName'=>'抢庄牛牛(高级场)'];
        $str[] = ['ServerID'=>75,'kindid'=>2,'ServerName'=>'抢庄牛牛(初级比赛场)'];
        $str[] = ['ServerID'=>76,'kindid'=>2,'ServerName'=>'抢庄牛牛(高级比赛场)'];
        $str[] = ['ServerID'=>80,'kindid'=>50,'ServerName'=>'幸运水果机(普通场)'];
        $str[] = ['ServerID'=>81,'kindid'=>50,'ServerName'=>'幸运水果机(贵宾场)'];
        $str[] = ['ServerID'=>90,'kindid'=>10,'ServerName'=>'通比炸金花(新手场)'];
        $str[] = ['ServerID'=>91,'kindid'=>10,'ServerName'=>'通比炸金花(初级场)'];
        $str[] = ['ServerID'=>92,'kindid'=>10,'ServerName'=>'通比炸金花(中级场)'];
        $str[] = ['ServerID'=>93,'kindid'=>10,'ServerName'=>'通比炸金花(高级场)'];
        $str[] = ['ServerID'=>95,'kindid'=>10,'ServerName'=>'通比炸金花(比赛场)'];
        $str[] = ['ServerID'=>96,'kindid'=>10,'ServerName'=>'通比炸金花(VIP比赛场)'];
        $str[] = ['ServerID'=>100,'kindid'=>20,'ServerName'=>'百人炸金花'];
        $str[] = ['ServerID'=>110,'kindid'=>65,'ServerName'=>'21点(新手场)'];
        $str[] = ['ServerID'=>111,'kindid'=>65,'ServerName'=>'21点(初级场)'];
        $str[] = ['ServerID'=>112,'kindid'=>65,'ServerName'=>'21点(中级场)'];
        $str[] = ['ServerID'=>113,'kindid'=>65,'ServerName'=>'21点(高级场)'];
        $str[] = ['ServerID'=>115,'kindid'=>65,'ServerName'=>'21点(初级比赛场)'];
        $str[] = ['ServerID'=>116,'kindid'=>65,'ServerName'=>'21点(高级比赛场)'];
        $str[] = ['ServerID'=>120,'kindid'=>30,'ServerName'=>'炸金花(新手场)'];
        $str[] = ['ServerID'=>121,'kindid'=>30,'ServerName'=>'炸金花(初级场)'];
        $str[] = ['ServerID'=>122,'kindid'=>30,'ServerName'=>'炸金花(中级场)'];
        $str[] = ['ServerID'=>123,'kindid'=>30,'ServerName'=>'炸金花(高级场)'];
        $str[] = ['ServerID'=>125,'kindid'=>30,'ServerName'=>'炸金花(比赛场)'];
        $str[] = ['ServerID'=>126,'kindid'=>30,'ServerName'=>'炸金花(高级比赛场)'];
        $str[] = ['ServerID'=>130,'kindid'=>3,'ServerName'=>'通比牛牛(新手场)'];
        $str[] = ['ServerID'=>131,'kindid'=>3,'ServerName'=>'通比牛牛(初级场)'];
        $str[] = ['ServerID'=>132,'kindid'=>3,'ServerName'=>'通比牛牛(中级场)'];
        $str[] = ['ServerID'=>133,'kindid'=>3,'ServerName'=>'通比牛牛(高级场)'];
        $str[] = ['ServerID'=>134,'kindid'=>3,'ServerName'=>'通比牛牛(至尊场)'];
        $str[] = ['ServerID'=>150,'kindid'=>80,'ServerName'=>'财神来了(新手场)'];
        $str[] = ['ServerID'=>151,'kindid'=>80,'ServerName'=>'财神来了(普通场)'];
        $str[] = ['ServerID'=>152,'kindid'=>80,'ServerName'=>'财神来了(高级场)'];
        $str[] = ['ServerID'=>160,'kindid'=>81,'ServerName'=>'水浒传(新手场)'];
        $str[] = ['ServerID'=>161,'kindid'=>81,'ServerName'=>'水浒传(普通场)'];
        $str[] = ['ServerID'=>162,'kindid'=>81,'ServerName'=>'水浒传(高级场)'];
        $str[] = ['ServerID'=>170,'kindid'=>85,'ServerName'=>'森林舞会'];*/
        S(array('type'=>'file','prefix'=>'gameroominfo','expire'=>60*60*24));
        $str = S('gameroom');
        if(empty($str)){
            $useraccount = M('','',"DB_CONFIG1");
            $str = $useraccount->table('cfg_gameroominfo')->field('ServerID,kindid,ServerName')->select();
            S('gameroom',$str);
        }
        return $str;
    }

    function getserverid($kindid){
        $msg="";
        foreach($this->getGameGerverId() as $n){
            if($n['kindid'] == $kindid){
                $msg .= $n['serverid'].",";
            }
        }
        return substr($msg,0,-1);
    }

    function getServerName($ServerID){
        foreach($this->getGameGerverId() as $n){
            if($n['serverid'] == $ServerID){
                return $n['servername'];
            }
        }
        return '';
    }


    /*
     * 没有权限 的处理
     */
    public function nop(){
        $this->display("Public/nopower");
        die;
    }

    /*
     * 找不到界面的处理 404
     */
    public function err404($msg , $errnum){
        $this->assign("msg",$msg);  //错误提示
        $this->assign("errnum",$errnum); //错误类型编码 404 505
        $this->display("Public/404");
        die;
    }

    /*
    * 处理结果提示 alert
     * 3 秒 后关闭
     *
     * $msg  提示说明
     * $errnum 错误码
     * $closetime   几秒后关闭窗口
    */
    public function alert($msg , $errnum ,$closetime){
        $this->assign("msg",$msg);  //错误提示
        $this->assign("errnum",$errnum); //错误类型编码 404 505
        $this->assign("closetime",$closetime); //几秒后关闭窗口  3000
        $this->display("Public/alert");
    }

    /*
     * 删除数组中指定的项
     * $arr  数组
     * $key  指定项
     */
    function del_arr_key($arr, $key){
        if(!array_key_exists($key, $arr)){
            return $arr;
        }
        $keys = array_keys($arr);
        $index = array_search($key, $keys);
        if($index !== FALSE){
            array_splice($arr, $index, 1);
        }
        //dump($arr);die;
        return $arr;
    }



    //日志记录
    public function logUrl(){
        Think\Log::write("{$_SERVER['REDIRECT_URL']}" ,'>>  URL');
    }
    /*
     * MYSQL 链接分装  日志库
     */
    protected function weblog($query_sql){
        if(empty($mysql1_con)){
            $servername = C('DB_HOST');
            $username = C('DB_USER');
            $password = C('DB_PWD');
            $dbname = C('DB_NAME');

            // 创建连接
            $conn = mysqli_connect($servername, $username, $password, $dbname);
            // 检测连接
            if (!$conn) {
                die("Connection failed1: " .iconv("gbk","utf-8",mysqli_connect_error()));
            }
            $mysql1 = $conn; //dump($mysql1); //链接留存
            $result = mysqli_query($conn, $query_sql);
            if(is_object($result)){ //select true
                if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_assoc($result)) {
                        $reset[] = $row;
                    }
                    return $reset;
                } else {
                    return ;
                }
            }elseif ($result===true){ //update delete insert
                return mysqli_affected_rows($conn); //受影响的行数
            }elseif($result === false){
                return  false;
            }
            // 释放内存
            mysqli_free_result($result);
            mysqli_close($conn);
        }
        die;
    }
    
     /*
     * MYSQL 链接分装  主库
     */
    protected function game($query_sql){
        if(empty($mysql1_con)){
            $arr = C('DB_CONFIG1');
            $servername = $arr['DB_HOST'];
            $username = $arr['DB_USER'];
            $password = $arr['DB_PWD'];
            $dbname = $arr['DB_NAME'];
            // 创建连接
            $conn = mysqli_connect($servername, $username, $password, $dbname);
            // 检测连接
            if (!$conn) {
                die("Connection failed2: " .iconv("gbk","utf-8",mysqli_connect_error()));
            }
            $mysql1 = $conn; //dump($mysql1); //链接留存
            $result = mysqli_query($conn, $query_sql);
            if(is_object($result)){ //select true
                if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_assoc($result)) {
                        $reset[] = $row;
                    }
                    return $reset;
                } else {
                    return ;
                }
            }elseif ($result===true){ //update delete insert
                return mysqli_affected_rows($conn); //受影响的行数
            }elseif($result === false){
                return  false;
            }

        }
        die;
    }
      /*
     * MYSQL 链接分装  web
     */
    protected function gamelog($query_sql){
        if(empty($mysql1_con)){
            $arr = C('DB_CONFIG2');
            $servername = $arr['DB_HOST'];
            $username = $arr['DB_USER'];
            $password = $arr['DB_PWD'];
            $dbname = $arr['DB_NAME'];
            // 创建连接
            $conn = mysqli_connect($servername, $username, $password, $dbname);
            // 检测连接
            if (!$conn) {
                die("Connection failed3: " .iconv("gbk","utf-8",mysqli_connect_error()));
            }
            $mysql1 = $conn; //dump($mysql1); //链接留存
            $result = mysqli_query($conn, $query_sql);
            if(is_object($result)){ //select true
                if (mysqli_num_rows($result) > 0) {
                    while($row = mysqli_fetch_assoc($result)) {
                        $reset[] = $row;
                    }
                    return $reset;
                } else {
                    return ;
                }
            }elseif ($result===true){ //update delete insert
                return mysqli_affected_rows($conn); //受影响的行数
            }elseif($result === false){
                return  false;
            }

        }
        die;
    }
 
    /*
     * sqlsrv1生成数据分页码
     * $p           第几页
     * $count       总记录条数
     * $listRows    每页条数
     */
    public function page_show($count,$listRows=10,$p=1){
        if(is_array($count))(
            $count=reset(reset($count))
        );
        $p_all = $count / intval($listRows);
        for ($i=1;$i< ($p_all+1);$i++){
            $show[] =$i;  //分页数组
        }
        if(count($show) > 5){
            $result[0]=$show[0]; //首页
            // if($p>5){
            //     $result[]=上;  // ...标记
            // }
            foreach ($show as $vo){
                if( abs($p-$vo)<4 ){
                    $result[]=$vo;
                }
            }
            // if(count($show) > 10  && $show[count($show)-5]>$p ){
            //     $result[]=下; //...标记
            // }
            $result[]=$show[count($show)-1]; //最后一页
            $result = array_unique($result);//数组去重
            return $result;
            die;
        }else{
            return $show;
        }
    }
    /**
     * 创建(导出)Excel数据表格
     * @param  array   $list 要导出的数组格式的数据
     * @param  string  $filename 导出的Excel表格数据表的文件名
     * @param  array   $header Excel表格的表头
     * @param  array   $index $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值)
     * 比如: $header = array('编号','姓名','性别','年龄');
     *       $index = array('id','username','sex','age');
     *       $list = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24));
     * @return [array] [数组]
     */
    protected function createtable($list,$filename,$header=array(),$index = array())
    {
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=" . $filename . ".xls");
        $teble_header = implode("\t", $header);
        $strexport = $teble_header . "\r";
        foreach ($list as $row) {
            foreach ($index as $val) {
                $strexport .= $row[$val] . "\t";
            }
            $strexport .= "\r";

        }
        $strexport = iconv('UTF-8', "GB2312//IGNORE", $strexport);
        exit($strexport);
    }
    /*
     * 创建(导出)Excel数据表格
     * 调用 方法演示
     */
    public function trycreatetable(){
        $filename = '提现记录'.date('YmdHis');
        $header = array('会员','编号','联系电话','开户名','开户行','申请金额','手续费','实际金额','申请时间');
        $index = array('id','card_no','card_owner','card_type','card_create_time','card_gold','user_game_id','user_nike_name','card_group');
        $cash = $this->sqlsrv1("SELECT distinct top 3  * FROM web_GameCard WHERE card_group  not in (SELECT top 2 card_group from web_GameCard)");
        $this->createtable($cash,$filename,$header,$index);
    }
    /*
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }

        return $obj;
    }
    
    //权限验证
    function CheckPower($power){
        if($_SESSION["ltq_game_admin_user"]['power']=='all')
            return 1;// $this->nop();//  return 1;
        $power=$power.',';
        if (strpos($_SESSION["ltq_game_admin_user"]['power'], $power)===false) {
            $this->nop();
        }
        return 1;
    }
    //获取主权限列表
    public  function GetMainPowers(){
        $result=[];
        if($_SESSION["ltq_game_admin_user"]['power']=='all')
        {
            $result[0]=1;
            return $result;
        }
        $result[0]=0;
        $power_list= explode(',',$_SESSION["ltq_game_admin_user"]['power']);
        array_pop($power_list); 
        foreach ($power_list as $key => $value) {
            if(strlen($value)<=2)
                $result[(int)$value]= 1;
        }
        return $result;
    }

    //通过ID返回当前用户的名称
    function Getusername($uid){
      if($uid){
        $where = 'where  id='.$uid;
      }
      // echo "SELECT name FROM ltq_admin $where";
      $lists = $this->weblog("SELECT name FROM ltq_admin $where");
      return $lists[0]['name'];
    }
    //通过accountid 返回名称
     function Getplayername($uid){
      if($uid){
        $where = 'where  accountid='.$uid;
      }
      $lists = $this->game("SELECT nikename FROM useraccount $where");
      return $lists[0]['nikename'];
    }
    /**记录操作日志
     * $id 操作对象id
     * $param_name 参数
     * $text 附加信息
     * 2013-10-23
     **/
    function actionLog($id,$a='',$m='',$param_name=''){
        $user_id = $_SESSION['ltq_game_admin_user']['id'];
        $user = M('admin')->where(array('id'=>$_SESSION['ltq_game_admin_user']['id']))->find();
        $category ='管理员';
        $data['user_id'] = $user_id;
        $action_name = strtolower(ACTION_NAME);
        $controller_name = strtolower(CONTROLLER_NAME);
        $controller_name = $controller_name;
        $action_name = strtolower(ACTION_NAME);
        $param_name = strtolower($param_name);
        $create_time = date('Y-m-d H:i:s');
        $action_id = $id;//L('ACTIONLOG',array($category,$user['name'],date('Y-m-d H:i:s'),L($data['action_name']),$id,L($controller_name),$text))
        $content = $category.$user['name'].'在'.date('Y-m-d H:i:s').$a.''.$id.'的'.$m;
        $user = M();
        $data['user_id']=$user_id;
        $data['controller_name']=$controller_name;
        $data['action_name']=$action_name;
        $data['param_name']=$param_name;
        $data['create_time']=$create_time;
        $data['action_id']=$action_id;
        $data['content']=$content;
        $user->table('data_logs')->add($data);
    }

// 类结束了
}

